﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseExemptionrule;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.Common.Core.Manager.Files;
using Microsoft.AspNetCore.Http;
using SHZY.Common.Helper;
using SHZY.BaseData.Entitys.Dto.QmsBaseInspectionrole;
using NPOI.SS.Formula.Functions;
using SHZY.system.Entitys;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;
using Spire.Xls;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：跳检规则分配.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Exemptionrule", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseExemptionruleService : IQmsBaseExemptionruleService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseExemptionruleEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 数据字典服务.
    /// </summary>
    private readonly IDictionaryDataService _dictionaryDataService;

    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseExemptionruleService"/>类型的新实例.
    /// </summary>
    public QmsBaseExemptionruleService(
        ISqlSugarRepository<QmsBaseExemptionruleEntity> qmsBaseExemptionruleRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IFileManager fileManager,
        IUserManager userManager,
        IDictionaryDataService dictionaryDataService)
    {
        _repository = qmsBaseExemptionruleRepository;
        _dataInterfaceService = dataInterfaceService;
        _db = context.AsTenant();
        _userManager = userManager;
        _fileManager = fileManager;
        _dictionaryDataService = dictionaryDataService;
    }

    /// <summary>
    /// 获取跳检规则分配.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseExemptionruleInfoOutput>();
    }

    /// <summary>
    /// 获取所有跳检规则分配信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.CreatorTime).ToListAsync();
        return new { list = data.Adapt<List<QmsBaseExemptionruleInfoOutput>>() };

    }

    /// <summary>
    /// 获取跳检规则分配列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseExemptionruleListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseExemptionruleEntity, DictionaryDataEntity, QmsBaseMaterialEntity, QmsBaseSupplierEntity, QmsBaseInspectionrolemainEntity>((a, b, c, d, e) => new JoinQueryInfos(
                JoinType.Left, a.OrderType == b.EnCode && b.DictionaryTypeId == "458162035063023429",
                JoinType.Left, a.Matnr == c.Code && c.DeleteMark == null,
                JoinType.Left, a.SupplierNo == d.Code && d.DeleteMark == null,
                JoinType.Left, a.RuleCode == e.Code && e.DeleteMark == null
            ))
            .WhereIF(!string.IsNullOrEmpty(input.matnr), a => a.Matnr.Equals(input.matnr))
            .WhereIF(!string.IsNullOrEmpty(input.orderType), a => a.OrderType.Equals(input.orderType))
            .WhereIF(!string.IsNullOrEmpty(input.supplierNo), a => a.SupplierNo.Equals(input.supplierNo))
            .WhereIF(!string.IsNullOrEmpty(input.ruleCode), a => a.RuleCode.Equals(input.ruleCode))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.Matnr.Contains(input.keyword) || a.OrderType.Contains(input.keyword) || a.SupplierNo.Contains(input.keyword) || a.RuleCode.Contains(input.keyword))
             .Where(a => a.DeleteMark == null)
             .Select((a, b, c, d, e) => new QmsBaseExemptionruleListOutput
             {
                 id = a.Id,
                 matnr = a.Matnr,
                 matnrDes = c.Name,
                 orderType = b.FullName,
                 supplierNo = d.Name,
                 ruleCode = e.Desc,
                 enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
             }).MergeTable();

        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }

        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBaseExemptionruleListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建跳检规则分配.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseExemptionruleCrInput input)
    {
        // fix:#同物料同供应商的数据，新增时需要卡控采购类型是否重复
        //if (await _repository.AnyAsync(x => x.Matnr == input.matnr && x.OrderType == input.orderType && x.SupplierNo == input.supplierNo && x.RuleCode == input.ruleCode && x.DeleteMark == null))
        if (await _repository.AnyAsync(x => x.Matnr == input.matnr && x.OrderType == input.orderType && x.SupplierNo == input.supplierNo && x.DeleteMark == null))
            throw Oops.Oh("当前配置已维护，请勿重复维护");
        var entity = input.Adapt<QmsBaseExemptionruleEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取跳检规则分配无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseExemptionruleListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseExemptionruleEntity, DictionaryDataEntity, QmsBaseMaterialEntity, QmsBaseSupplierEntity, QmsBaseInspectionrolemainEntity>((a, b, c, d, e) => new JoinQueryInfos(
                JoinType.Left, a.OrderType == b.EnCode && b.DictionaryTypeId == "458162035063023429",
                JoinType.Left, a.Matnr == c.Code && c.DeleteMark == null,
                JoinType.Left, a.SupplierNo == d.Code && d.DeleteMark == null,
                JoinType.Left, a.RuleCode == e.Code && e.DeleteMark == null
            ))
            .WhereIF(!string.IsNullOrEmpty(input.matnr), a => a.Matnr.Equals(input.matnr))
            .WhereIF(!string.IsNullOrEmpty(input.orderType), a => a.OrderType.Equals(input.orderType))
            .WhereIF(!string.IsNullOrEmpty(input.supplierNo), a => a.SupplierNo.Equals(input.supplierNo))
            .WhereIF(!string.IsNullOrEmpty(input.ruleCode), a => a.RuleCode.Equals(input.ruleCode))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.Matnr.Contains(input.keyword) || a.OrderType.Contains(input.keyword) || a.SupplierNo.Contains(input.keyword) || a.RuleCode.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), a => a.Id);
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        var data = await queryable.Select((a, b, c, d, e) => new QmsBaseExemptionruleListOutput
        {
            id = a.Id,
            matnr = a.Matnr,
            matnrDes = c.Name,
            orderType = b.FullName,
            supplierNo = d.Name,
            ruleCode = e.Desc,
            enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
        }).ToListAsync();
        return data;
    }

    /// <summary>
    /// 导出跳检规则分配.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseExemptionruleListQueryInput input)
    {
        var exportData = new List<QmsBaseExemptionruleListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseExemptionruleListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"物料号\",\"field\":\"matnr\"},{\"value\":\"采购类型\",\"field\":\"orderType\"},{\"value\":\"供应商\",\"field\":\"supplierNo\"},{\"value\":\"跳检规则\",\"field\":\"ruleCode\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "跳检规则分配.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value, Width = 25 });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseExemptionruleListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除跳检规则分配.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseExemptionruleEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除客户信息
                var isOk = await _repository.Context.Updateable<QmsBaseExemptionruleEntity>().SetColumns(it => new QmsBaseExemptionruleEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新跳检规则分配.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseExemptionruleUpInput input)
    {
        if (await _repository.AnyAsync(x => x.Matnr == input.matnr && x.OrderType == input.orderType && x.SupplierNo == input.supplierNo && x.RuleCode == input.ruleCode && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh("当前配置已维护，请勿重复维护");
        var entity = input.Adapt<QmsBaseExemptionruleEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除跳检规则分配.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBaseExemptionruleEntity>().SetColumns(it => new QmsBaseExemptionruleEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };

        }
        catch (Exception ex)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] QmsBaseExemptionruleImportDataInput input)
    {
        var output = new QmsBaseExemptionruleImportDataOutput();
        //获取采购类型字典项
        var orderTypeList = await _dictionaryDataService.GetList("orderType");
        //获取物料信息数据
        var matnrList = await _repository.Context.Queryable<QmsBaseMaterialEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).ToListAsync();
        //获取供应商数据
        var supplierList = await _repository.Context.Queryable<QmsBaseSupplierEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).ToListAsync();
        //获取跳检规则数据
        var inspectionrolemainList = await _repository.Context.Queryable<QmsBaseInspectionrolemainEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).ToListAsync();
        foreach (var item in input.list)
        {
            try
            {
                string exceptionMsg = "";
                if (string.IsNullOrWhiteSpace(item.matnr) || string.IsNullOrWhiteSpace(item.orderType) || string.IsNullOrWhiteSpace(item.supplierNo) || string.IsNullOrWhiteSpace(item.ruleCode))
                {
                    exceptionMsg += "物料,类型,供应商,规则均不能为空";
                }
                var orderType = orderTypeList.Find(x => x.FullName == item.orderType);
                if (orderType == null)
                {
                    exceptionMsg += "采购类型不存在";
                }
                var matnr = matnrList.Find(x => x.Name == item.matnr);
                if (matnr == null)
                {
                    exceptionMsg += "物料信息不存在";
                }
                var supplier = supplierList.Find(x => x.Name == item.supplierNo);
                if (supplier == null)
                {
                    exceptionMsg += "供应商不存在";
                }
                var inspectionrolemain = inspectionrolemainList.Find(x => x.Desc == item.ruleCode);
                if (inspectionrolemain == null)
                {
                    exceptionMsg += "跳检规则不存在";
                }
                if (!exceptionMsg.Equals("")) throw Oops.Oh(exceptionMsg);

                var entity = item.Adapt<QmsBaseExemptionruleEntity>();
                entity.OrderType = orderType.EnCode;
                entity.Matnr = matnr.Id;
                entity.SupplierNo = supplier.Id;
                entity.RuleCode = inspectionrolemain.Id;
                var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOK < 1)
                {
                    output.failResult.Add(item);
                    output.fnum++;
                }
                else
                {
                    output.snum++;
                }
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
        }
        else
        {
            output.resultType = 0;
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "跳检规则分配模板.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "exemptionrule_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!(await _fileManager.ExistsFile(addFilePath)))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {

            throw Oops.Oh(ErrorCode.D1801);
        }
    }

    /// <summary>
    /// 获取字段编码.
    /// </summary>
    /// <param name="filed"></param>
    /// <returns></returns>
    private string GetFileEncode(string filed)
    {
        switch (filed)
        {
            case "物料号":
                return "matnr";
            case "采购类型":
                return "orderType";
            case "供应商":
                return "supplierNo";
            case "跳检规则":
                return "ruleCode";
            default:
                return string.Empty;
        }

    }



}